package com.dxy.dxyadmin.controller;

import com.dxy.dxyadmin.VO.AdminVO;
import com.dxy.dxycommon.VO.ResultVO;
import com.dxy.dxycommon.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * junfeng 2018/11/9 管理员登录控制器
 */
@RestController
@Slf4j
@RequestMapping("/admin")
public class LoginController {

    @CrossOrigin
    @RequestMapping(value = "/login", consumes = "application/json")
    public ResultVO login(@RequestBody AdminVO admin) {
        // shrio:登陆逻辑
        // 获取认证对象的包装对象
        Subject subject = SecurityUtils.getSubject();

        if (subject != null && subject.isAuthenticated()) {
            return ResultVOUtil.success();
        }
        // 获取一个认证的令牌:
        // 直接获取页面的用户和密码进行校验
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(admin.getName(), admin.getPassword());

        String name = admin.getName();
        try {
            subject.login(usernamePasswordToken);
        } catch (IncorrectCredentialsException ice) {
            log.info("对用户【" + name + "】进行登录验证，验证未通过，错误的凭证！");
            return ResultVOUtil.error("登录失败！错误的凭证！！！");
        } catch (UnknownAccountException uae) {
            log.info("对用户【" + name + "】进行登录验证，验证未通过，未知账户！");
            return ResultVOUtil.error("登录失败！未知账户！！！");
        } catch (LockedAccountException lae) {
            log.info("对用户【" + name + "】进行登录验证，验证未通过，账户锁定！");
            return ResultVOUtil.error("登录失败！验证未通过，账户锁定！！！");
        } catch (ExcessiveAttemptsException eae) {
            log.info("对用户【" + name + "】进行登录验证，验证未通过，错误次数太多！");
            return ResultVOUtil.error("登录失败！验证未通过，错误次数太多！！！");
        } catch (AuthenticationException ae) {
            log.info("对用户【" + name + "】进行登录验证，验证未通过，堆栈轨迹如下：！");
            ae.printStackTrace();
            return ResultVOUtil.error("登录失败！用户名或者密码错误！！！");
        }

        if (subject.isAuthenticated()) {
            subject.getSession().setAttribute("admin", admin);
        } else {
            usernamePasswordToken.clear();
            return ResultVOUtil.error("登录失败！");
        }

        return ResultVOUtil.success();
    }


}
